package stock;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Component
public class StockSuanFaImpl implements StockSuanFa {

	@SuppressWarnings("unused")
	@Autowired
	private ProjectSession projectSession;

	@PersistenceContext
	private EntityManager entityManager;

	@Override
	public List<Stock> zhang_die5(Float zhang, Float die) {
		// TODO Auto-generated method stub
		System.out.println("---------------开始查询--------------------");
		List<JSONObject> list = new ArrayList<JSONObject>();
		Session session1 = ContextUtil.getSessionFactory1().openSession();
		String sql0 = "select DISTINCT(t.code) from Stock t ";
		String sql4 = "from StockCode t where t.code = ?0";
		List<String> list0 = session1.createQuery(sql0).list();
		String sql5 = "delete from stock_code_suan_fa where 1=1 ";
		session1.beginTransaction();
		session1.createSQLQuery(sql5).executeUpdate();
		session1.getTransaction().commit();
		session1.clear();
		for (int i = 0; i < list0.size(); i++) {
			System.out.println("--------正在计算--" + list0.get(i) + "-------------------");
			String code = list0.get(i);
			String sql1 = " select count(*) from Stock t where  t.code = ?0 and t.zhandifu >= 5 ORDER BY t.date desc ";
			String sql2 = " select count(*) from Stock t where  t.code = ?0 and t.zhandifu <= -5 ORDER BY t.date desc ";
			Object zhang5 = (Object) session1.createSQLQuery(sql1).setParameter(0, code).uniqueResult();
			Object die5 = (Object) session1.createSQLQuery(sql2).setParameter(0, code).uniqueResult();
			List<StockCode> listsc = session1.createQuery(sql4).setParameter(0, code).list();
			if (listsc != null && listsc.size() > 0) {
				session1.beginTransaction();
				StockCodeSuanFa scsf = new StockCodeSuanFa();
				scsf.setStockCode(listsc.get(0).getCode());
				scsf.setStockName(listsc.get(0).getName());
				scsf.setDieN(Integer.parseInt(die5 + ""));
				scsf.setZhangN(Integer.parseInt(zhang5 + "")); 
				session1.save(scsf);
				
				session1.getTransaction().commit();
				session1.clear();
			} else {
				session1.beginTransaction();
				StockCodeSuanFa scsf = new StockCodeSuanFa();
				scsf.setStockCode(code);
				String sql6 = "from Stock t where t.code = ?0";
				List<Stock> listStock = session1.createQuery(sql6).setParameter(0, code).setMaxResults(1).setFirstResult(0).list();
				scsf.setStockName(listStock.get(0).getName());
				scsf.setDieN(Integer.parseInt(die5 + ""));
				scsf.setZhangN(Integer.parseInt(zhang5 + ""));
				session1.save(scsf);
				session1.getTransaction().commit();
				session1.clear();
			}

		}
		session1.close();
		return null;
	}

}
